<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Api_MessageController extends Zend_Rest_Controller
{
	public function init()
	{
		$this->_helper->viewRenderer->setNoRender(true);
	}


	public function deleteAction() {

	}

	public function getAction() {
		try{
			$message_mapper = new Api_Model_MessageMapper();
			$message_id = $this->_getParam('id');

			if ($message_id != NULL){

				$message_mapper->readMessage($message_id);
				throw new Exception(json_encode(array('meta' => 'OK')),200);
			} else {
				throw new Exception(json_encode(array('meta' => 'Bad request')),400);
			}

		}catch(Exception $e){
			$this->getresponse()->appendBody($e->getMessage());
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}
	}

	public function headAction() {

	}

	public function indexAction() {
		try{
			$message_mapper = new Api_Model_MessageMapper();
			$user_id = $this->_getParam('param1');

			if ($user_id != NULL){

				$messages = $message_mapper->getAllMessage($user_id);
				$this->getresponse()->appendBody(json_encode($messages));
				$this->getResponse()->setHttpResponseCode(200);
			} else {
				throw new Exception(json_encode(array('meta' => 'Bad request')),400);
			}

		}catch(Exception $e){
			$this->getresponse()->appendBody($e->getMessage());
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}
	}

	public function getusermessageAction() {
		try{
			$message_mapper = new Api_Model_MessageMapper();
			$sender = $this->_getParam('param1');
			$receiver = $this->_getParam('param2');
			if ($sender != NULL && $receiver != NULL){

				$messages = $message_mapper->getconversationMessage($sender, $receiver);
				$this->getresponse()->appendBody(json_encode($messages));
				$this->getResponse()->setHttpResponseCode(200);
			} else {
				throw new Exception(json_encode(array('meta' => 'Bad request')),400);
			}

		}catch(Exception $e){
			$this->getresponse()->appendBody($e->getMessage());
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}
	}

	public function postAction() {
		try{
			$message_mapper = new Api_Model_MessageMapper();
			$rawBody = $this->getRequest()->getRawBody();
			$data = Zend_Json::decode($rawBody);

			if ($data['receiver'] != "" || $data['sender'] != "" || $data['content'] != ""){

				$message = $message_mapper->sendMessage($data);

				$this->getresponse()->appendBody(json_encode($message));
				$this->getResponse()->setHttpResponseCode(201);

			} else {
				throw new Exception(json_encode(array('meta' => 'Bad request')),400);
			}

		}catch(Exception $e){
			$this->getresponse()->appendBody($e->getMessage());
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}
	}

	public function putAction() {

	}
}
